package io;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
@Slf4j
public class SerializeDemo {

    public static void main(String[] args) {
        // 序列化
        // serObj();
        // 反序列化
        objSer();

    }

    public static void serObj() {
        BaseOperationLogEntity e = new BaseOperationLogEntity();
        e.setStartTime(System.currentTimeMillis());
        e.setRelationId("123");
        e.setType("type");
        e.setLevel("info");
        e.setDetail("详情");
        try {
            // 获取资源文件夹的绝对路径
            String resourcePath = new File("src/main/resources/tmp").getAbsolutePath();
            File directory = new File(resourcePath);

            // 确保目标文件夹存在
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    throw new IOException("无法创建目标文件夹");
                }
            }

            // 构建目标文件路径
            File dest = new File(directory, "log.ser");

            // 创建文件输出流
            FileOutputStream fileOut = new FileOutputStream(dest);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(e);
            out.close();
            fileOut.close();
            System.out.printf("Serialized data is saved in %s%n", dest.getAbsolutePath());
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
    public static void objSer() {
        BaseOperationLogEntity e = null;
        try {
            // 获取资源文件夹的绝对路径
            String resourcePath = new File("src/main/resources/tmp").getAbsolutePath();
            File dest = new File(resourcePath, "log.ser");

            // 检查文件是否存在
            if (!dest.exists()) {
                throw new FileNotFoundException("文件不存在: " + dest.getAbsolutePath());
            }

            // 创建文件输入流
            FileInputStream fileIn = new FileInputStream(dest);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (BaseOperationLogEntity) in.readObject();
            in.close();
            fileIn.close();
            System.out.printf("Deserialized data: %s%n", e);
        } catch (FileNotFoundException fnf) {
            System.out.println("文件未找到: " + fnf.getMessage());
            fnf.printStackTrace();
        } catch (IOException i) {
            System.out.println("IO 异常: " + i.getMessage());
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            System.out.println("BaseOperationLogEntity 类未找到");
            c.printStackTrace();
        }
        log.info("反序列化结果：{}", e);
    }
}
